//
//  UIColor+IGColor.m
//  XYLib
//
//  Created by blts on 2017/6/12.
//  Copyright © 2017年 Richard. All rights reserved.
//

#import "UIColor+IGColor.h"

@implementation UIColor (IGColor)
+ (UIColor *)colorWithRGBHex:(UInt32)hex {
    int r = (hex >> 16) & 0xFF;
    int g = (hex >> 8) & 0xFF;
    int b = (hex) & 0xFF;
    
    return [UIColor colorWithRed:r / 255.0f
                           green:g / 255.0f
                            blue:b / 255.0f
                           alpha:1.0f];
}

+(UIColor *)colorWithStr:(NSString *)colorStr
{
    //    NSString *color = @“#FF0000”;
    // 转换成标准16进制数
    //    [colorStr replaceCharactersInRange:[colorStr rangeOfString:@"#"] withString:@"0x"];
    colorStr = [colorStr stringByReplacingOccurrencesOfString:@"#" withString:@"0x"];
//    [colorStr stringByReplacingOccurrencesOfString:@"#" withString:@"0x"];
    // 十六进制字符串转成整形。
    long colorLong = strtoul([colorStr cStringUsingEncoding:NSUTF8StringEncoding], 0, 16);
    // 通过位与方法获取三色值
    int R = (colorLong & 0xFF0000 )>>16;
    int G = (colorLong & 0x00FF00 )>>8;
    int B =  colorLong & 0x0000FF;
    
    //string转color
    UIColor *color = [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:1.0];
    return color;
}

+(UIColor *)colorWithStr:(NSString *)colorStr WithAlpha:(CGFloat)alpha
{
    //    NSString *color = @“#FF0000”;
    // 转换成标准16进制数
    //    [colorStr replaceCharactersInRange:[colorStr rangeOfString:@"#"] withString:@"0x"];
    colorStr = [colorStr stringByReplacingOccurrencesOfString:@"#" withString:@"0x"];
    //    [colorStr stringByReplacingOccurrencesOfString:@"#" withString:@"0x"];
    // 十六进制字符串转成整形。
    long colorLong = strtoul([colorStr cStringUsingEncoding:NSUTF8StringEncoding], 0, 16);
    // 通过位与方法获取三色值
    int R = (colorLong & 0xFF0000 )>>16;
    int G = (colorLong & 0x00FF00 )>>8;
    int B =  colorLong & 0x0000FF;
    
    //string转color
    UIColor *color = [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:alpha];
    return color;
}

//  颜色转换为背景图片

+ (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
    
}
@end
